<template>
  <div class="content_index">
    <div class="ci_header">
      <div class="ci_left">凭证列表</div>
    </div>
    <div class="ci_note">
      <DescriptionBlock data="展示凭证列表" />
    </div>
    <div class="ci_des">
      <div style="display: flex">
        <el-button plain @click="VoucherCreate()" v-if="userType == '1' || userType == '3'">凭证申请</el-button>
      </div>
      <div style="display: flex">
        <!-- <el-select
                v-model="searchUserStatus"
                clearable
                placeholder="请选择用户状态"
                style="margin-right: 10px"
              >
                <el-option label="正常" value="1" />
                <el-option label="停用" value="0" />
        </el-select>-->
        <!-- 搜索框 -->
        <el-input
          style="margin-right: 10px"
          class="ci_input"
          v-if="userType == '1' || userType == '3'"
          v-model="issuerName"
          clearable
          placeholder="请输入发证方名称"
        ></el-input>
        <el-input
          style="margin-right: 10px"
          class="ci_input"
          clearable
          v-model="credentialName"
          placeholder="请输入凭证名称"
        ></el-input>
        <div @click="search">
          <!-- <Search class="iconfont__header_icon" /> -->
          <el-button plain>查询</el-button>
        </div>
        <!-- <div class="iconfont icon-zhongzhireset" @click="fresh">
                <RefreshRight class="iconfont__header_icon" />
        </div>-->
      </div>
    </div>
    <div class="ci_content">
      <div class="table_list">
        <div class="tl_table">
          <el-table
            v-loading="VoucherLoading"
            :data="tableData"
            height="100%"
            width="100%"
            :header-cell-style="tableHeaderStyle"
            :cell-style="tableCellStyle"
          >
            <el-table-column prop="credentialId" label="编号" width="150">
              <template v-slot="scope">
                <el-tooltip effect="light" :content="scope.row.credentialId" placement="top">
                  <div class="center_start">
                    <span
                      @click="VoucherInfo(scope)"
                      :class="userType == '1' || userType == '3' ? 'info_style' : ''"
                      class="ellipsis"
                    >{{ scope.row.credentialId }}</span>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="credentialName" label="凭证名称" />
            <el-table-column
              prop="issuerName"
              label="发证方名称"
              v-if="userType == '1' || userType == '3'"
            />
            <el-table-column
              prop="issuerDid"
              v-if="userType == '1' || userType == '3'"
              label="发证方DID"
            >
              <template v-slot="scope">
                <el-tooltip effect="light" :content="scope.row.issuerDid" placement="top">
                  <div class="center_start">
                    <span class="ellipsis">{{ scope.row.issuerDid }}</span>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="cptId" label="CPT编号">
              <template v-slot="scope">
                <el-tooltip effect="light" :content="scope.row.cptId" placement="top">
                  <div class="center_start">
                    <span class="ellipsis">{{ scope.row.cptId }}</span>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="凭证状态">
              <template v-slot="scope">
                <div class="center_start">
                  <span class="ellipsis">{{ type[scope.row.status] }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column prop="updatedTime" label="更新时间" />
            <el-table-column prop label="操作">
              <template v-slot="scope">
                <div class="center_start">
                  <span
                    v-if="userType == '1' || userType == '3'"
                    @click="VoucherEmpower(scope)"
                    style="font-size: 12px; cursor: pointer; color: #409eff"
                  >授权</span>
                  <span
                    v-if="userType == '2'"
                    @click="revoke(scope)"
                    style="font-size: 12px; cursor: pointer; color: #409eff"
                  >吊销</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="tl_table_pagination">
          <el-pagination
            background
            @size-change="handleSizeChange"
            :hide-on-single-page="page.isPageHide"
            @current-change="handleCurrentChange"
            :current-page.sync="page.pageNo"
            :page-size="page.pageSize"
            :page-sizes="[10, 15, 20, 30]"
            layout="total, prev, pager, next, sizes"
            :total="page.totalCount"
          ></el-pagination>
        </div>
      </div>
      <el-dialog
        :width="dialogWidth"
        :title="userType == '1' || userType == '3' ? '凭证授权' : '凭证吊销'"
        :close-on-click-modal="false"
        :modelValue="dialogVisible"
        :destroy-on-close="true"
        @close="clearForm"
      >
        <div>
          <el-form
            label-position="right"
            ref="addVoucherFormRef"
            label-width="120px"
            :model="addVoucherForm"
            :rules="rules"
          >
            <el-form-item label="凭证名称：" prop>{{ VoucherEmpowerName }}</el-form-item>
            <el-form-item v-if="userType == '2'" label="吊销原因：" prop="revokeReason">
              <el-input type="textarea" v-model="addVoucherForm.revokeReason" placeholder="请输入吊销原因"></el-input>
            </el-form-item>
            <el-form-item v-if="userType == '1' || userType == '3'" label="被授权DID：" prop="grantee">
              <el-input v-model="addVoucherForm.grantee" placeholder="请输入被授权DID"></el-input>
            </el-form-item>
            <el-form-item v-if="userType == '1' || userType == '3'" label="到期时间：" prop="exp">
              <el-date-picker v-model="addVoucherForm.exp" type="datetime" placeholder="请输入到期时间" />
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer center">
          <el-button @click.prevent="certificateAuthority" type="primary" :loading="isLoading">确定</el-button>
          <el-button plain @click="VoucherCancel">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
      
      <script setup>
import { DescriptionBlock } from "@/components/index";
import { tableHeaderStyle, tableCellStyle } from "@/utils/tableStyle";
import {
  VoucherListApi,
  EmpowerCreateApi,
  VoucherDeleteApi
} from "@/api/Voucher";
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { dateToStringBySecond } from "@/utils/tool";
import store from "@/store";
const router = useRouter();
const VoucherLoading = ref(false);
const userType = ref("");
const issuerName = ref("");
const credentialName = ref("");
const VoucherEmpowerName = ref("");
const credentialId = ref("");
const dialogVisible = ref(false);
const isLoading = ref(false);
const page = reactive({
  pageSize: 10,
  pageNo: 1,
  isPageHide: false,
  totalPage: 0,
  totalCount: 0
});
const dialogWidth = ref("600px");
const tableData = ref([]);
const type = ref({
  0: "待审核",
  1: "正常",
  2: "吊销"
});
const addVoucherForm = reactive({
  grantee: "",
  allow: "R",
  exp: "",
  revokeReason: ""
});
/** 表单校验规则 */
const rules = {
  grantee: [
    {
      required: true,
      message: "请输入被授权DID",
      trigger: "blur"
    }
  ],
  revokeReason: [
    {
      required: true,
      message: "限制100位字符以内",
      trigger: "blur"
    },
    {
      max: 100,
      message: "限制100位字符以内",
      trigger: "blur"
    }
  ],
  exp: [
    {
      required: true,
      message: "请选择到期时间",
      trigger: "blur"
    }
  ]
};
const addVoucherFormRef = ref("addVoucherForm");
const search = () => {
  getVoucherList();
};
const VoucherInfo = data => {
  if (userType.value == "1" || userType.value == "3") {
    let id = data.row.credentialId;
    router.push({ path: "/VoucherManagement/VoucherInfo", query: { id } });
  }
};
const handleSizeChange = val => {
  page.pageNo = 1;
  page.pageSize = val;
  getVoucherList();
};
const handleCurrentChange = val => {
  page.pageNo = val;
  getVoucherList();
};
const setDialogWidth = () => {
  let val = document.body.clientWidth * 0.6;
  const def = 600; // 默认宽度
  if (val < def) {
    dialogWidth.value = "60%";
  } else {
    dialogWidth.value = def + "px";
  }
};
const VoucherCreate = () => {
  router.push({ path: "/VoucherManagement/VoucherCreate" });
};
const VoucherEmpower = data => {
  VoucherEmpowerName.value = data.row.credentialName;
  credentialId.value = data.row.credentialId;
  dialogVisible.value = true;
};
const revoke = data => {
  VoucherEmpowerName.value = data.row.credentialName;
  credentialId.value = data.row.credentialId;
  dialogVisible.value = true;
};
const VoucherCancel = () => {
  dialogVisible.value = false;
  clearForm();
};
const clearForm = () => {
  dialogVisible.value = false;
  addVoucherFormRef.value?.resetFields();
};
const getVoucherList = () => {
  let parmars = {
    pageNum: page.pageNo,
    pageSize: page.pageSize,
    issuerName: issuerName.value,
    credentialName: credentialName.value
  };
  VoucherLoading.value = true;
  VoucherListApi(parmars)
    .then(res => {
      if (res.success && res.data) {
        VoucherLoading.value = false;
        tableData.value = res.data.list || [];
        page.totalCount = res.data.totalCount;
      } else {
        VoucherLoading.value = false;
      }
    })
    .catch(err => {
      ElMessage.error(err.msg);
      VoucherLoading.value = false;
    });
};
const certificateAuthority = () => {
  addVoucherFormRef.value?.validate(async valid => {
    if (valid) {
      isLoading.value = true;
      if (userType.value == "1" || userType.value == "3") {
        let parmars = {
          objectId: credentialId.value,
          ...addVoucherForm
        };
        delete parmars["revokeReason"];
        parmars.exp = parmars.exp ? dateToStringBySecond(parmars.exp) : "";
        const { success, msg } = await EmpowerCreateApi(parmars);
        if (success) {
          isLoading.value = false;
          dialogVisible.value = false;
          ElMessage.success(msg || "凭证授权成功");
          getVoucherList();
        } else {
          isLoading.value = false;
          ElMessage.error(msg || "凭证授权失败,请稍后再试");
        }
      } else if (userType.value == "2") {
        let parmars = {
          credentialId: credentialId.value,
          ...addVoucherForm
        };
        delete parmars["allow"];
        delete parmars["exp"];
        delete parmars["grantee"];
        const { success, msg } = await VoucherDeleteApi(parmars);
        if (success) {
          isLoading.value = false;
          dialogVisible.value = false;
          ElMessage.success(msg || "凭证吊销成功");
          getVoucherList();
        } else {
          isLoading.value = false;
          ElMessage.error(msg || "凭证吊销失败,请稍后再试");
        }
      }
    } else {
      return false;
    }
  });
};
onMounted(() => {
  userType.value = store.userStore?.user?.userType;
  setDialogWidth();
  getVoucherList();
});
</script>
      <style lang="scss" scoped>
@import "../../assets/css/list.scss";
@import "../../assets/css/position.scss";

.content_index {
  :deep.el-input {
    width: 90%;
    max-width: 400px;
  }
  :deep .iconfont__header_icon {
    width: 16px;
    margin-top: 8px;
  }
  .title_personal {
    font-size: 16px;
    font-weight: 700;
  }
  .tl_table_pagination {
    width: 100%;
    display: flex;
    justify-content: end;
    padding-right: 16px;
  }
}
.content_index {
  :deep.el-select {
    width: 95%;
    border-radius: 0;

    :deep .el-input {
      width: 95%;
      border-radius: 0 !important;
    }
    .el-input__suffix {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      border-radius: 0;
      font-size: 12px;
    }
  }
}

.aitem {
  cursor: pointer;
  color: #2186fb;
}

.nodata_tips {
  margin-left: 5px;
  color: #2186fb;
  cursor: pointer;
}
.info_style {
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
}
</style>